import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.io.IOException;
import java.util.Scanner;

public class UDPClient {
    private static final int PORT = 9090;
    private static final String SERVER_ADDRESS = "localhost";

    public static void main(String[] args) {
        try {
            startUdpClient();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void startUdpClient() throws Exception {
        Scanner scanner = new Scanner(System.in);
        DatagramSocket socket = new DatagramSocket();
        System.out.println("tips: 输入 'exit' 服务器退出,'bye' 客户端退出");
        while (true) {
            System.out.println("请输入你要传输的信息 :");
            String message = scanner.nextLine();

            if ("bye".equals(message)) {
                System.out.println("客户端退出...");
                break;
            }

            // 构造UDP数据包
            InetAddress serverAddress = InetAddress.getByName(SERVER_ADDRESS);
            DatagramPacket packet = new DatagramPacket(message.getBytes(), message.length(), serverAddress, PORT);
            socket.send(packet);

            System.out.println("消息已发送到服务器： " + message);
        }

        socket.close();
    }
}
